<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
    </theme-navbar>
    <!-- #endif -->

    <view class="content u-page" :style="`padding-bottom: ${isOperateAuth ? 140 : 2}rpx; min-height: calc(100% - ${isOperateAuth ? 140 : 2}rpx);`">
      <u-form ref="uForm" :model="formData">
        <!-- 发起信息 -->
        <u-card v-if="['02', '03', '04', '05', '06', '07'].indexOf(formData.taskStatus) > -1" title="发起信息" style="margin-left: 0; margin-right: 0;">
          <view slot="body">
              <u-form-item label="任务紧急程度" label-width="auto">
                <text>{{ allTaskUrgencyLevel[formData.taskUrgencyLevel] }}</text>
              </u-form-item>
              <u-form-item label="协同问题项" label-position="top" label-width="auto">
                <view
                  class="group-tag"
                  v-for="(item, index) of coordTypeList"
                  :key="index"
                >
                  <view class="group-name">{{ item.coordTypeName }}</view>
                  <view class="group-tag-list">
                    <u-tag
                      v-for="tagItem of item.tags.filter(item => !!item)"
                      :text="tagItem.text"
                      :key="tagItem.value"
                      style="margin: 0 20rpx 20rpx 0; padding: 18rpx 22rpx; font-size: 28rpx;"
                    />
                  </view>
                </view>
              </u-form-item>
              <u-form-item label="反馈时间" prop="feedbackTime" borderBottom label-width="auto">
                <u-input
                  placeholder="请选择"
                  v-model="formData.feedbackTime"
                  disabled
                  @click="handleFeedbackTimeClick"
                />
              </u-form-item>
              <u-form-item label="反馈地点" prop="feedbackPlace" borderBottom label-width="auto">
                <u-input placeholder="请填写" v-model="formData.feedbackPlace" disabled />
              </u-form-item>
              <u-form-item label="具体位置" prop="location" borderBottom label-width="auto">
                <u-input placeholder="请选择" v-model="formData.location" disabled />
              </u-form-item>
              <u-form-item label="备注说明" label-position="top">
                <u-input type="textarea" v-model="formData.taskNote" disabled />
              </u-form-item>
              <view>
                <upload-images
                  :canAdd="false"
                  :canDel="false"
                  :url="uploadFile"
                  :length="10"
                  :extForm="{fiGroupCode: $FILE_GROUP_TYPE.grid_fusio_task_img, bizId: formData.taskUuid}"
                  :bizId="formData.taskUuid"
                  :del-url="delUrl"
                  :can-add="true"
                  :can-del="true"
                  :renderImages="getImages($FILE_GROUP_TYPE.grid_fusio_task_img)"
                  ref="saveModel3"
                  style="padding-left: 0;"
                ></upload-images>
              </view>
          </view>
        </u-card>

        <!-- 任务核查 -->
        <template v-if="['03', '04', '05', '06', '07'].indexOf(formData.taskStatus) > -1">

          <view v-if="['03', '04'].indexOf(formData.taskStatus) > -1 && !isOperateAuth" style="text-align: center; margin: 30rpx 0; color: #999;">任务待核查中...</view>

          <u-card v-else title="处理信息" style="margin-left: 0; margin-right: 0;">
            <view slot="body">
              <u-form-item label="线索分值" label-width="auto">
                <u-input type="number" placeholder="请输入分值" v-model="formData.cueScore" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" />
              </u-form-item>
              
              <u-form-item label="案件信息" label-width="auto">
                <view style="flex: 1;">
                  <u-icon v-if="['03', '04'].indexOf(formData.taskStatus) > -1" style="float:right;" :color="$theme.u_type_primary" name="plus" size="38" @click="handleAddCaseClick"></u-icon>
                </view>
              </u-form-item>
              <view v-if="caseList.length" class="case-list" style="padding-top: 20rpx;">
                
                <view class="case-list-item" v-for="(caseItem, index) of caseList" :key="caseItem.caseUuid">
                  <u-swipe-action
                    :index="index"
                    :show="caseItem.show"
                    :options="actionOptions"
                    @click="handleActionClick(caseItem)"
                    @open="handleSwipeOpen(index)"
                  >
                  <case-info-item :sealInfo="caseItem" style="margin: 10rpx 15rpx;">
                  </case-info-item>
                  </u-swipe-action>
                </view>
              </view>

              <u-form-item v-for="item of taskResultItem" :key="item.value" :label="item.text" label-width="auto">
                <!-- <u-input placeholder="请输入处理结果" v-model="formData.tasksResultList[item.value]" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" /> -->
              
                <!-- 文本框类型 -->
                <u-input v-if="item.coordOperateType === '91403'" placeholder="请输入处理结果" v-model="formData.tasksResultList[item.value]" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" />
                
                <!-- 是否单选框 -->
                <template v-if="item.coordOperateType === '91401'" >
                  <z-dict-radio :dictType="$u.dic.DIC_KEYS.S_SYS_YES_NO" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" v-model="formData.tasksResultList[item.value]"></z-dict-radio>
                </template>

                <!-- 字典选择器 -->
                <template v-if="item.coordOperateType === '91402'" >
                  <z-dict-select :dictType="item.contentOptions" :readOnly="!(['03', '04'].indexOf(formData.taskStatus) > -1)" v-model="formData.tasksResultList[item.value]" @confirm="handleDictConfirm"></z-dict-select>
                </template>
                
                <!-- 日期 -->
                <template v-if="item.coordOperateType === '91422'" >
                  <u-input placeholder="请选择日期" v-model="formData.tasksResultList[item.value]" disabled @click="handleDateClick(item.value, !(['03', '04'].indexOf(formData.taskStatus) > -1))" />
                  <u-icon slot="right" name="arrow-right"></u-icon>
                </template>

                <!-- 文本域 -->
                <u-input v-if="item.coordOperateType === '91404'" type="textarea" v-model="formData[item.value]" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" />
              
              </u-form-item>

              <u-form-item label="备注信息" label-position="top">
                <u-input type="textarea" v-model="formData.resultRemark" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" />
              </u-form-item>
              <upload-images
                :canAdd="['03', '04'].indexOf(formData.taskStatus) > -1 && isOperateAuth"
                :canDel="['03', '04'].indexOf(formData.taskStatus) > -1"
                :url="uploadFile"
                :length="10"
                :extForm="{fiGroupCode: $FILE_GROUP_TYPE.grid_fusio_task_img_hc, bizId: formData.taskUuid}"
                :bizId="formData.taskUuid"
                :del-url="delUrl"
                :renderImages="getImages($FILE_GROUP_TYPE.grid_fusio_task_img_hc)"
                ref="saveModel3"
                style="padding-left: 0;"
              ></upload-images>
            </view>
          </u-card>
        </template>


        <template v-if="['05', '06', '07'].indexOf(formData.taskStatus) > -1">

          <view v-if="['05'].indexOf(formData.taskStatus) > -1 && !isOperateAuth" style="text-align: center; margin: 30rpx 0; color: #999;">任务待审核中...</view>

          <u-card v-else  title="审核信息" style="margin-left: 0; margin-right: 0;">
            <view slot="body">
              <u-form-item label="审核意见" label-position="top">
                <u-input type="textarea" v-model="formData.approveRemark" :disabled="!(formData.taskStatus == '05' && isOperateAuth)" />
              </u-form-item>
            </view>
          </u-card>

        </template>


        <u-card title="审批历史" style="margin-left: 0; margin-right: 0;">
          <view slot="body" style="padding: 0 20rpx;">
            <flow-his-no-doc :bizUuid="formData.taskUuid" :processDefKey="flowCode" :endTitle="formData.taskStatus === '07' ? '结束' : ''"></flow-his-no-doc>
          </view>
        </u-card>
      </u-form>

      

    </view>

    

    <template v-if="isOperateAuth">
      <!-- 派单 -->
      <view v-if="formData.taskStatus == '02'" class="submit-btns btn-other-cls">
        <u-button class="u-btn" type="success" @click="handleAudit('01')">派单</u-button>
        <u-button class="u-btn" type="error" @click="handleAudit('03')">退回</u-button>
      </view>

      <!-- 协同反馈 -->
      <view v-if="['03', '04'].indexOf(formData.taskStatus) > -1" class="submit-btns btn-other-cls">
        <u-button class="u-btn" type="primary" @click="handleSaveTaskResult">保存</u-button>
        <u-button class="u-btn" type="success" @click="handleAudit('01')">提交</u-button>
        <u-button class="u-btn" type="error" @click="handleAudit('03')">退回</u-button>
      </view>

      <!-- 协同审核 -->
      <view v-if="['05'].indexOf(formData.taskStatus) > -1" class="submit-btns btn-other-cls">
        <u-button class="u-btn" type="success" @click="handleAudit('01')">提交</u-button>
        <u-button class="u-btn" type="error" @click="handleAudit('03')">退回</u-button>
      </view>

      <!-- 协同确认 -->
      <view v-if="['06'].indexOf(formData.taskStatus) > -1" class="submit-btns btn-other-cls">
        <u-button class="u-btn" type="success" @click="handleAudit('01')">确认</u-button>
      </view>
    </template>

    <u-modal
      title="提示"
      :show-cancel-button="true"
      cancel-text="取消"
      v-model="flowReturnShow"
      @confirm="handleFlowReturnConfirm"
      content="确认退回吗？"
    />

    <!-- 日期选择器 -->
    <u-picker v-if="datePickerShow" mode="time" v-model="datePickerShow" :default-time="formData[currSelCoordType]" :params="timeParams" @confirm="handleDatePickerConfirm"></u-picker>

  </view>
</template>

<script>
import commonService from '@/service/eCigar/common.service';
import intelligenceservice from "@/service/intelligence/intelligence.service";
import tripleNetworkIntegrationService from "@/service/tripleNetworkIntegration/tripleNetworkIntegration.service.js";
import { UploadImages } from "@/components";
import caseInfoItem from './components/caseInfoItem.vue';
import flowHisNoDoc from "@/components/flow-his-no-doc.vue";
import { ZDictRadio, ZDictSelect } from '@/components';


const allTaskUrgencyLevel = {
  "01": "一般",
  "02": "紧急",
  "03": "特急"
};

export default {
  components: {
    UploadImages,
    caseInfoItem,
    flowHisNoDoc,
    ZDictRadio,
    ZDictSelect
  },
  data() {
    return {
      flowCode: "gridFusionTask",
      user: this.$store.state.userInfo,
      loading: true,
      formData: {
        tasksResultList: {}
      },
      caseList: [],
      allTaskUrgencyLevel,
      allBusinessList: [], // 所有业务指标
      filePath: [],

      uploadFile: commonService.uploadFile,
      delUrl: commonService.deleteFile,

      flowReturnShow: false,

      rules: [],

      timeParams: {
				year: true,
				month: true,
				day: true,
				hour: false,
				minute: false,
				second: false
			},
      currSelCoordType: "",
      datePickerShow: false,
    };
  },
  computed: {
    coordTypeList() {
      let currBusinessList = this.allBusinessList.filter(item => item.businessType == this.formData.businessType);

      let currCoordTypeList = [];
      let itemUuids = this.formData.itemUuidArray || [];

      if (currBusinessList.length) {
        currCoordTypeList = currBusinessList[0].coordTypeList.map(coordTypeItem => {
          coordTypeItem.tags = coordTypeItem.coordItemList.map(coordItem => {
            if(itemUuids.indexOf(coordItem.itemUuid) > -1) {
              return { text: coordItem.itemName, value: coordItem.itemUuid, ...coordItem }
            }
            
          })
          return coordTypeItem;
        })
      }

      currCoordTypeList = currCoordTypeList.map(item => {
        if (item.tags) {
          item.tags = item.tags.filter(item => !!item);
        }
        return item;
      });
      currCoordTypeList = currCoordTypeList.filter(item => item.tags && item.tags.length);

      return currCoordTypeList;
    },
    taskResultItem() {
      let list = [];
      this.coordTypeList.map(item => {
        item.tags.map(tagItem => {
          list.push(tagItem);
        });
      });
      return list;
    },
    // 是否具有页面操作权限
    isOperateAuth() {
      let flag = false;

      console.log(this.user);
      let handlePersonUuids = this.formData.handlePersonUuids || "";
      if (handlePersonUuids.indexOf(this.user.user.personUuid) > -1) {
        flag = true;
      }
      return flag;
    },
    actionOptions() {
      if (["03", "04"].indexOf(this.formData.taskStatus) > -1) {
        return [{
          text: "删除",
          style: {
            backgroundColor: "#dd524d",
          },
        }]
      } else {
        return []
      }
    }
  },
  onLoad(options) {
    let routeParams = this.getRouteParam();
    if (options.taskUuid) {
      this.formData.taskUuid = options.taskUuid;
    } else if (routeParams.taskUuid) {
      this.formData.taskUuid = routeParams.taskUuid;
    }

    this.getGridFusionTaskTaskInfo(this.formData.taskUuid);
    this.getGridFusionTaskItem();
  },
  methods: {
    handleAddCaseClick() {
      this.$u.route({
        url: "/pages/commonPage/selectCase",
      });
    },
    handleSwipeOpen(index) {
      this.caseList[index].show = true;
      this.caseList.map((val, idx) => {
        if (index != idx) this.caseList[idx].show = false;
      });
    },
    handleActionClick(data) {
      this.caseList = this.caseList.filter(item => item.caseUuid !== data.caseUuid)
    },
    // 获取任务详情
    getGridFusionTaskTaskInfo(taskUuid) {
      this.$modal.showLoading('加载中...');
      let paras = { taskUuid };
      this.loading = true;
      tripleNetworkIntegrationService.getGridFusionTaskTaskInfo(paras).then(res => {
        this.$modal.hideLoading();
        this.loading = false;
        if (res.success) {
          if(!taskUuid) {
            this.formData = { ...res.bean};
          } else {
            // 详情
            const { taskResultList, task, caseList, approveResult } = res.bean;

            this.formData = {
              ...task,
              tasksResultList: taskResultList || {}, // 处理反馈信息
              resultRemark: taskResultList.resultRemark || "", // 处理反馈备注
              approveRemark: approveResult ? approveResult.approveResult : "", // 审核意见
            };
            this.caseList = caseList || [];
          }
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("数据获取失败!");
        this.$modal.hideLoading();
      });
    },
    // 获取所有指标类型
    getGridFusionTaskItem() {
      tripleNetworkIntegrationService.getGridFusionTaskItem({
        taskUuid: this.formData.taskUuid
      }).then(res => {
        if (res.success) {
          this.allBusinessList = res.data;
        } else {
          this.$u.toast(res.msg);
        }
      });
    },
    getImages(fileGroup) {
      return () => new Promise((res, rej) => {
        this.renderImages(fileGroup).then(data => {
          res(data)
        }).catch(() => {
          rej([])
        })
      });
    },
    renderImages(fileGroup){
      return new Promise((res, rej) => {
        intelligenceservice.findFilesByBizIdAndGroup({
          bizId: this.formData.taskUuid,
          group: fileGroup,
        }).then(r => {
					if(r.code == 200 && r.success && Array.isArray(r.data)) {
						r.data.forEach(i => {
							i.src = `${commonService.baseUrl}/commonfile/filestore/downloadFile.do?fileId=${i.gfiId}&tk=${uni.getStorageSync("tk")}`;
              i.filePath = i.src;
						});
						res(r.data);
					} else {
					 res([]);
					}
				});
			})
    },
    updateBackState(param) {
      if (param["flowUserSelectBack"]) {
        // 审核人员选择回调
        let nextPersonUuids = param["flowUserSelectBack"].map(item => item.personId).join(",");

        this.formData.nextPersonUuids = nextPersonUuids;
        this.auditGridFusionTask();
      } else if (param["selectCase"]) {
        this.caseList = param.selectCase;
      }
    },
    // 验证任务处理结果表单
    validTaskResultData() {
      let flag = true;
      let msgText = "";

      for(let i=0; i<this.taskResultItem.length; i++) {
        let item = this.taskResultItem[i];
        if (!this.formData.tasksResultList[item.value]) {
          flag = false;
          msgText = "请输入"+item.text;
          break;
        }
      }

      if (!flag) {
        this.$u.toast(msgText);
        return false;
      } else if (!this.formData.resultRemark) {
        this.$u.toast("请输入处理备注信息!");
        return false;
      } else if (!this.formData.cueScore) {
        this.$u.toast("请输入分值!");
        return false;
      } else {
        return true;
      }
    },
    // 处理表单数据
    getFormData() {
      let formData = JSON.parse(JSON.stringify(this.formData));

      // 任务处理结果项
      if (Object.keys(formData.tasksResultList)) {
        let checkArr = Object.keys(formData.tasksResultList).map(key => {
          if (key === "resultRemark") {
            return;
          }
          return { itemUuid: key, checkResult: formData.tasksResultList[key] }
        });
        formData.tasksResultList = checkArr.filter(item => !!item);
      }

      if (this.caseList.length) {
        formData.caseUuid = this.caseList.map(item => item.caseUuid).join(",");
      }
      
      return formData; 
    },
    // 保存任务处理结果
    handleSaveTaskResult() {
      let valid = this.validTaskResultData();

      if (!valid) {
        return;
      }
      this.saveGridFusionTaskResult(this.getFormData());
    },
    // 保存任务处理结果
    saveGridFusionTaskResult(params) {
      this.$modal.showLoading("数据保存中...");
      tripleNetworkIntegrationService.saveGridFusionTaskResult(params).then(res => {
        if (res.success) {
          this.$u.toast("数据保存成功!");
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("数据保存失败!");
      })
    },

    // 获取流程获选人参数
    getNextFlowUsersExtData() {
      this.$modal.showLoading("获取候选人中...");
      tripleNetworkIntegrationService.getNextFlowUsersExtData({
        taskUuid: this.formData.taskUuid,
        businessType: this.formData.businessType
      }).then(res => {
        if (res.success) {
          let extParams = res.bean || {};
          this.setRouteParam({
            ...extParams
          });
          this.$u.route({
            url: "/pages/commonPage/flowUserSelectComponent",
            params: {
              flowFormCode: this.flowCode,
            }
          });
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("候选人获取失败!");
      })
    },
    /**
     * 处理流程审批
     * @param {*} approveResult 审核类型 01(审核)、03(退回)
     */
    handleAudit(approveResult) {

      this.formData.approveResult = approveResult;

      if (approveResult === "01") {
        if (["03", "04"].indexOf(this.formData.taskStatus) > -1) {
          // 问题审核阶段
          let valid = this.validTaskResultData();
          if (valid) {
            this.getNextFlowUsersExtData();
          }
        } else if (this.formData.taskStatus === "05" && this.formData.businessType === "05") {
          // 审核阶段，任务类型为烟草类的，审核完直接结束流程，反之进入待确认流程
          if (!this.formData.approveRemark) {
            this.$u.toast("请输入审核意见!");
            return;
          }
          this.auditGridFusionTask();
        } else if (this.formData.taskStatus === "06") {
          this.auditGridFusionTask();
        } else {
          this.getNextFlowUsersExtData();
        }
      } else {
        // 退回
        this.flowReturnShow = true;
      }
    },
    // 退回模态框确认回调
    handleFlowReturnConfirm() {
      this.auditGridFusionTask();
    },
    /**
     * 流程审批
     */
    auditGridFusionTask() {
      this.$modal.showLoading('流程提交中...');
      tripleNetworkIntegrationService.auditGridFusionTask(this.getFormData()).then(res => {
        this.$modal.hideLoading();
        if (res.success) {
          this.$u.toast("操作成功!");
          setTimeout(() => {
            this.backPrev({
              paramKey: "submitSuccess",
              param: true
            });
          }, 1000);
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("操作失败!");
        this.$modal.hideLoading();
      })
    },
    handleDateClick(type, disabled) {
      if (disabled) {
        return;
      }
      this.datePickerShow = true;
      this.currSelCoordType = type;
    },
    handleDatePickerConfirm(e) {
      this.formData.tasksResultList[this.currSelCoordType] = `${e.year}-${e.month}-${e.day}`;
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 0;
}
.content {
  background-color: #f3f4f5;
}

.card {
  margin-left: 0;
  margin-right: 0;
  border-radius: 0;
  padding-left: 25rpx;
  padding-right: 25rpx;
}

.group-tag {
  .group-name {
    font-size: 30rpx;
    font-weight: 600;
    margin: 0;
  }
}
</style>